/*
 * @author: pizigou
 * @date: 2009-11-5
 */
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include "handle_file.h"

static block_item item;

static int status_right, status_wrong, is_continue=0;
/**
 * 
 * analyse data file
 */
void parse_file(file *p_file)
{
	FILE *fp;
	site_handle handle;
	
	fp = fopen(p_file->file_name, "r");
	if (!fp) {
		printf("error: open %s failed\n", p_file->file_name);
		return;
	}
	handle.fp = fp;
	handle.p_file = p_file;

	/** 
	 * handle
	 */
	while (!feof(fp)) handle_file(&handle);

	fclose(fp);
}

/**
 * calc right or wrong state
 */
static void calc_state()
{
	int i = 0;
	while (i < MAX_CHECK_LINES && item.sites[i].server[0] != '\0') {
		//printf("server:%s,status:%d\n", item.sites[i].state);
		if (item.sites[i].state == 1) status_right++;
		else status_wrong++;
		i++;
	}
}

/**
 * fill site_block struct
 */
static void handle_file(site_handle *p_handle)
{
	int i = 0;
	int no = 0;

	if (is_continue == 0) is_continue = 1; // make this function can not called more times at it's end
	else return;

	if (item.sites[MAX_CHECK_LINES - 1].server[0] != '\0') no = item.sites[MAX_CHECK_LINES - 1].no;
	memset(item.sites, '\0', sizeof(site_block) * MAX_CHECK_LINES);
	while (p_handle->fp && !feof(p_handle->fp) && i < MAX_CHECK_LINES) {
		fscanf(p_handle->fp, "%s %s %s\n",  item.sites[i].mail, item.sites[i].server, item.sites[i].port);
		item.sites[i].no = ++no;
		i++;
	}
	item.block_num = i;
	p_handle->p_file->p_handle_site(&item);

	calc_state();
	is_continue = 1;
	//save_state(p_handle->p_file->file_name);
}

/**
 * serilize result
 */
void save_state(float f)
{
	FILE *fp;
	struct tm *tm_ptr;
	time_t t;
	char file_name[1024] = {"\0"};
	char dir[1024] = {"\0"};
	char *r;
	int len;
	char time_format[30] = {"\0"};
	
	time(&t);
	tm_ptr = localtime(&t);

	sprintf(time_format, "%.4d-%.2d-%.2d", \
						tm_ptr->tm_year + 1900, tm_ptr->tm_mon + 1, tm_ptr->tm_mday
			);
	if (arg.dir != NULL) {
		len = strlen(arg.dir);
		r = strrchr(arg.dir, '/');
		if (*r == 0) *(arg.dir + len - 1) = "\0";
		sprintf(dir, "%s/%s", arg.dir, time_format);
	} else {
		sprintf(dir, "./%s", time_format);
	}
	mkdir(dir, S_IRWXU);
	memset(time_format, "\0", 30);
	sprintf(time_format, "%.4d-%.2d-%.2d %.2d:%.2d:%.2d", \
						tm_ptr->tm_year + 1900, tm_ptr->tm_mon + 1, tm_ptr->tm_mday, \
						tm_ptr->tm_hour, tm_ptr->tm_min, tm_ptr->tm_sec \
			);
	sprintf(file_name, "%s/%s", dir, time_format);
	if ((fp = fopen(file_name, "w+")) != NULL) {
		fprintf(fp, "live:%d\nunlive:%d\ntime used:%fs\ntime end:%s\n", status_right, status_wrong, f, time_format);
		fclose(fp);
	} else printf("create file '%s' failed\n", file_name);
}
